<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="courseTitle">
        <el-input
          v-model="queryParams.courseTitle"
          placeholder="请输入课程名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="培训学期" prop="semeId">
        <template>
          <el-select v-model="queryParams.semeId" placeholder="请选择" @change="getList()">
            <el-option
              v-for="item in semeList"
              :key="item.semeId"
              :label="item.semeName"
              :value="item.semeId">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="所属合班" prop="mergeClassId">
        <el-input
          v-model="queryParams.mergeClassId"
          placeholder="请输入所属合班ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['psedu-base:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['psedu-base:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['psedu-base:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['psedu-base:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程ID" align="center" prop="courseId" fixed/>
      <el-table-column label="课程名称" align="center" prop="courseTitle" fixed/>
      <el-table-column label="上课范围" align="center" prop="deptScope" />
      <el-table-column label="封面图片链接" align="center" prop="imageUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50" v-if="scope.row.imageUrl !== null && scope.row.imageUrl !== ''"/>
        </template>
      </el-table-column>
      <el-table-column label="实现的ID" align="center" prop="realizeCourseId" />
      <el-table-column label="上课地点" align="center" prop="classroom" />
      <el-table-column label="课程内容" align="center" prop="content" />
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="授课教师" align="center" prop="teacher" />
      <el-table-column label="需要评教" align="center" prop="evaluate" />
      <el-table-column label="课程开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRealizeCourse(scope.row)"
            v-hasPermi="['psedu-base:course:add']"
            v-show="scope.row.realizeCourseId === 0"
          >实现</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleSign(scope.row)"
          >签到情况</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleStartLive(scope.row)"
          >开始直播</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['psedu-base:course:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['psedu-base:course:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程名称" prop="courseTitle">
          <el-input v-model="form.courseTitle" placeholder="请输入课程名称" />
        </el-form-item>
<!--        <el-form-item label="培训学期" prop="semeId">-->
<!--          <el-input v-model="form.semeId" placeholder="请输入培训学期" />-->
<!--        </el-form-item>-->
        <el-form-item label="所属合班ID" prop="mergeClassId">
          <el-input v-model="form.mergeClassId" placeholder="请输入所属合班" />
        </el-form-item>
        <el-form-item label="封面图片链接">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
        <el-form-item label="实现的ID" prop="realizeCourseId" v-show="form.realizeCourseId !== 0">
          <el-input v-model="form.realizeCourseId" placeholder="请输入实现的ID"/>
        </el-form-item>
        <el-form-item label="上课地点" prop="classroom">
          <el-input v-model="form.classroom" placeholder="请输入上课地点" />
        </el-form-item>
        <el-form-item label="签到坐标">
          <el-link
            type="primary"
            @click="openMap"
          >点击打开地图</el-link>
          <div>
            经度：{{ this.mapDialog.lat }} 纬度：{{this.mapDialog.lng }}
          </div>
        </el-form-item>
        <el-form-item label="签到时间">
          <el-radio-group>
            <el-date-picker
              v-model="signLaunch.signDateTimeRange"
              type="datetimerange"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="签到距离">
          <el-input v-model="signLaunch.accuracy"></el-input>
        </el-form-item>
        <el-form-item label="课程内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher">
          <el-input v-model="form.teacher" placeholder="请输入授课教师" />
        </el-form-item>
        <el-form-item label="需要评教" prop="evaluate">
          <el-input v-model="form.evaluate" placeholder="请输入需要评教" />
        </el-form-item>
        <el-form-item label="课程开始时间" prop="startTime">
          <el-date-picker clearable size="small"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择课程开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="课程学习视频">
          <file-upload v-model="form.videoUrl" :fileType="['mp4']" :fileSize="500"/>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable size="small"
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="mapDialog.title" :visible.sync="mapDialog.open">
      <div id="mapContainer"></div>
      <div slot="footer" class="dialog-footer">
        <el-button>关闭</el-button>
        <el-button type="primary" @click="mapDialog.open = false">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourse, getCourse, delCourse, addCourse, updateCourse } from "@/api/psedu-base/course";
import { listSimpleSemester } from "@/api/psedu-base/semester"

export default {
  name: "Course",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseTitle: null,
        semeId: this.$route.query.semeId *1,
        mergeClassId: null,
        realizeCourseId: null,
        evaluate: null,
      },
      semeList: [],
      // 表单参数
      form: {
      },
      signLaunch: {
        signDateTimeRange: [],
      },
      // 表单校验
      rules: {
        courseTitle: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        semeId: [
          { required: true, message: "培训学期不能为空", trigger: "blur" }
        ],
      },
      mapDialog: {
        title: '地图',
        open: false,
        lat: '', //j
        lng: '' //w
      },
    };
  },
  created() {
    this.getSemeList();
    this.getList();
  },
  methods: {
    /** 学期列表 */
    getSemeList() {
      listSimpleSemester().then(resp => {
        console.log(resp);
        this.semeList = resp.data;
      })
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.mapDialog = {
        title: '地图',
        open: false,
        lat: '', //j
        lng: '' //w
      }
      this.signLaunch = {};
      this.form = {
        courseId: null,
        courseTitle: null,
        semeId: null,
        deptId: null,
        mergeClassId: null,
        imageUrl: null,
        videoUrl: null,
        realizeCourseId: 0,
        deptScope: null,
        classroom: null,
        content: null,
        orderNum: null,
        teacher: null,
        evaluate: null,
        startTime: null,
        endTime: null,
        createTime: null,
        updateTime: null,
        deleted: null,
        createBy: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程";
      this.form.semeId = this.queryParams.semeId;
    },
    handleStartLive(row) {
      this.$tab.openPageWithParam("课程直播", "/train/psedu-live/live/start", {
        courseId: row.courseId
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err);
      });
    },
    /** 实现课程 */
    handleRealizeCourse(row) {
      this.reset();
      const courseId = row.courseId || this.ids
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.form.realizeCourseId = row.courseId
        this.form.courseId = null;
        this.title = "实现课程";
      });

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const courseId = row.courseId || this.ids
      getCourse(courseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程";
        this.signLaunch = response.data.signLaunch ?? {};
        this.mapDialog.lng = this.signLaunch.longitude ?? null;
        this.mapDialog.lat = this.signLaunch.latitude ?? null;
        if(this.signLaunch.startTime) {
          this.signLaunch.signDateTimeRange = [this.signLaunch.startTime, this.signLaunch.endTime];
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log(this.signLaunch.signDateTimeRange)
        if(this.signLaunch.signDateTimeRange) {
          this.signLaunch.startTime =  this.signLaunch.signDateTimeRange[0];
          this.signLaunch.endTime =  this.signLaunch.signDateTimeRange[1];
        }
        this.form.signLaunch = this.signLaunch;
        this.form.signLaunch.longitude = this.mapDialog.lng
        this.form.signLaunch.latitude = this.mapDialog.lat
        console.log(this.form)
        if (valid) {
          if (this.form.courseId != null) {
            updateCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.courseId || this.ids;
      this.$modal.confirm('是否确认删除课程编号为"' + courseIds + '"的数据项？').then(function() {
        return delCourse(courseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('psedu-base/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    },
    handleSign(row) {
      this.$tab.openPageWithParam(row.courseTitle +"签到情况", "/train/signRecord", {
        courseId: row.courseId
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err);
      });
    },
    openMap() {
      this.mapDialog = {
        title: '地图',
        open: true,
        lat: '', //j
        lng: '' //w
      }
      this.$nextTick(() => {
        let map = new BMapGL.Map('mapContainer') // 创建Map实例
        map.centerAndZoom(
          new BMapGL.Point(112.927988, 27.908385),
          17
        ) // 初始化地图,设置中心点坐标和地图级别
        map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
        let marker2
        let menu = new BMapGL.ContextMenu()
        let txtMenuItem = [
          {
            text: '放大一级',
            callback: function() {
              map.zoomIn()
            }
          },
          {
            text: '缩小一级',
            callback: function() {
              map.zoomOut()
            }
          }
        ]
        for (let i = 0; i < txtMenuItem.length; i++) {
          menu.addItem(
            new BMapGL.MenuItem(
              txtMenuItem[i].text,
              txtMenuItem[i].callback,
              100
            )
          )
        }
        map.addEventListener('click', e => {
          if (marker2) {
            this.mapDialog.lng = e.latlng.lng
            this.mapDialog.lat = e.latlng.lat
            this.$forceUpdate()
            return
          }
          let status = confirm('您确定该地为签到地点吗？')
          console.log(e)

          if (status) {
            marker2 = new BMapGL.Marker(
              new BMapGL.Point(e.latlng.lng, e.latlng.lat),
              {
                enableDragging: true
              }
            )
            map.addOverlay(marker2)
            this.mapDialog.lng = e.latlng.lng
            this.mapDialog.lat = e.latlng.lat
            this.$forceUpdate()
          }
        })
      })
    },
  },
};
</script>

<style scoped>
  #mapContainer {
    overflow: hidden;
    width: 100%;
    /* height: 100%; */
    height: 600px;
    margin: 0;
    font-family: '微软雅黑';
  }
</style>
